import os
import re

path = "/var/log/snort"
#path = "D:/Desktop/tmp"

def task(number=1623952782):
    alerts = []
    logs = []
    global path
    dirs = os.listdir(path)
    for file in dirs:
        #print (file)
        alertObj = re.match(r'alert\.(\d+)',file)
        if alertObj:
            alerts.append(alertObj.group(1))
        else:
            logObj = re.match(r'snort\.log\.(\d+)',file)
            if logObj:
                logs.append(logObj.group(1))
    alerts.sort()
    #print(alerts)
    while len(alerts)>5:
        file_string = alerts.pop(0)
        os.remove("{}/alert.{}".format(path,file_string))
    logs.sort()
    #print(logs)
    while len(logs)>5:
        file_string = logs.pop(0)
        os.remove("{}/snort.log.{}".format(path,file_string))
    last_number = len(alerts)-1
    if int(alerts[last_number]) > int(number):
        analysis_alert(alerts[last_number])
    return alerts[last_number]

def analysis_alert(number_file):
    global path
    table = {}
    with open("{}/alert.{}".format(path,number_file),'r') as f:
        for line in f.readlines():
            
            if "TCP session without 3-way handshake" in line:
                continue
            if "NO CONTENT-LENGTH OR TRANSFER-ENCODING IN HTTP RESPONSE" in line:
                continue
            info_cell = analysis_line(line)
            if len(info_cell) != 0:
                if info_cell[0] not in table:
                    table[info_cell[0]] = {}
                key_string = "{}->{}".format(info_cell[1],info_cell[2])
                if key_string not in table[info_cell[0]]:
                    table[info_cell[0]][key_string] = 0
                table[info_cell[0]][key_string] = table[info_cell[0]][key_string]+1

    with open("result.txt.{}".format(number_file),'w') as f:
        for key in table:
            f.write("{}:\n".format(key))
            if len(table[key])<20:
                for key1 in table[key]:
                    f.write("    {}-----{}\n".format(key1,table[key][key1]))
            else:
                for key1 in table[key]:
                    if table[key][key1] > 10:
                        f.write("    {}-----{}\n".format(key1,table[key][key1]))
    print("完成")

def analysis_line(line):
    result = []
    pattern = re.compile(r'^\S+\s+\[\*\*\](.*)\[\*\*\]\s+\[.*\]\s+\[.*\]\s+\{.*\}\s+(\d+\.\d+\.\d+\.\d+)(?:\:\d+)?\s+->\s+(\d+\.\d+\.\d+\.\d+)(?:\:\d+)?')
    
    searchObj = pattern.match(line)
    if searchObj:
        alert_info = searchObj.group(1).strip()
        result.append(alert_info)
        source_ip = searchObj.group(2)
        result.append(source_ip)
        dst_ip = searchObj.group(3)
        result.append(dst_ip)
    else:
        print(line)
        print("失败")
    return result

if __name__ == '__main__':
    print(task())